﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace FrameWork.DataHelper
{
    public static class ModelBuilderConfig
    {
        /**
         * 获取子单模型
         */
        public static void CreateModel<T, TKey>(this ModelBuilder modelBuilder, Expression<Func<T, IEnumerable<T>>> collection, Expression<Func<T, TKey>> key) where T : class
        {
            // 获取集合导航属性的名称（在这里 `collection` 表达式是一个 Lambda 表达式）
            var collectionProperty = (MemberExpression)collection.Body;
            var collectionPropertyName = collectionProperty.Member.Name;

            // 获取外键的属性名称
            var keyProperty = (MemberExpression)key.Body;
            var keyPropertyName = keyProperty.Member.Name;

            modelBuilder.Entity<T>()
                .HasMany(collection)
                .WithOne()
                .HasForeignKey(keyPropertyName);
        }
    }
}
